package com.rhb.af.dao;

import java.io.Serializable;

import java.util.*;

import com.rhb.af.bean.BaseQuery;
import com.rhb.af.util.HibernateSupport;

import org.hibernate.Query;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class GeneralDAO_Hql_SpringHibernateImpl extends HibernateDaoSupport implements
		GeneralDAO {

	public void save(Object obj) {
		this.getHibernateTemplate().saveOrUpdate(obj);
	}
	
	public void create(Object obj) {
		this.getHibernateTemplate().save(obj);
	}

	public void update(Object obj) {
		this.getHibernateTemplate().merge(obj);
	}
	
	public void delete(Object obj) {
		this.getHibernateTemplate().delete(this.getHibernateTemplate().merge(obj));
	}
	
	public Object findByPK(Class clazz,Serializable pk) {
		return this.getHibernateTemplate().get(clazz, pk);
	}

	public int countByQuery(BaseQuery query) {	
		Long allcount = new Long(0);
		//Query q = HibernateDaoTools.getQuery(this.getSession(), query, true);
			
		Query q = HibernateSupport.getQuery(this.getSession(), query, true);
		Iterator result = q.iterate();

		if (result.hasNext()) {
			allcount = (Long) result.next();
		}
		return allcount.intValue();
	}

	public List findByQuery(BaseQuery query) {
		//Query q = HibernateDaoTools.getQuery(this.getSession(), query, false);
		Query q = HibernateSupport.getQuery(this.getSession(), query, false);
		q.setFirstResult(query.getStart());
		q.setMaxResults(query.getCount());
		return q.list();
	}
	
	public List<Object[]> findBySql(String sql, int start, int count) {
		Query q = this.getSession().createSQLQuery(sql);
		q.setFirstResult(start);
		q.setMaxResults(count);
		return q.list();
	}
}
